package com.titaniume.java;

/**
 *@program: JavaSenior
 *@description: 使用同步方法解决继承Thread类的线程安全问题
 *
 *  关于同步方法的总结：
 * 1.同步方法任然涉及到同步监视器，只是不需要我们显示的声明
 * 2. 非静态的同步方法，同步监视器是this
 *    静态的同步方法，同步监视器是当前类本身
 *
 *
 *
 *
 *@author: renfei.huang
 *@create: 2021-09-29 14:18
 */
public class WindowTest4 {

    public static void main(String[] args) {

        Window4 t1 = new Window4();
        Window4 t2 = new Window4();
        Window4 t3 = new Window4();


        t1.setName("窗口一");
        t2.setName("窗口二");
        t3.setName("窗口三");

        t1.start();
        t2.start();
        t3.start();
    }
}


class Window4 extends Thread {

    private static int ticket = 100;

    @Override
    public void run() {
        while (true) {
            show();
        }
    }

    private  static synchronized void show(){  //同步监视器：Window4.class
        //  private  synchronized void show() 是错误的 //同步监视器 t1, t2,t3
        if (ticket > 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "：卖票，票号为:" + ticket);
            ticket--;
        }
    }
}


